# !/usr/bin/env python
# File       : article.py
# Time       : 2022/8/29 15:18
# Author     : hyx
# -*- coding:utf-8 -*-
# 文章
from flask import Blueprint, render_template, redirect, request, url_for, g, flash

from bluelog.decorators import login_required
from forms import AnswerForm
from modle import QuestionModel, CategoryModel, AnswerModel
from ext import db, csrf

article = Blueprint('article', __name__, url_prefix='/')

# 创建过滤器
@article.app_template_filter('cdecode')
def content_decode(content):
    content = content.decode('utf-8')
    return content


@article.route('/')
def home():
    return redirect(url_for('article.index', page=1))


@article.route('/ceshi/')
def ceshi():
    return render_template('ceshi.html')

# 首页
@article.route('/page_<int:page>/#', methods=['GET'])
def index(page):
    articles = QuestionModel.query.order_by(QuestionModel.create_time.desc()).paginate(page=page, per_page=9,
                                                                                       error_out=False)
    categories = CategoryModel.query.all()
    return render_template('index.html', articles=articles, categories=categories)


# 分类渲染
@article.route('/kind_<int:category_id>/page_<int:page>/#', methods=['GET'])
def kind_index(category_id, page=1):
    articles = QuestionModel.query.filter(QuestionModel.category_id == category_id).order_by(
        QuestionModel.create_time.desc()).paginate(page=page, per_page=9,
                                                   error_out=False)
    categories = CategoryModel.query.all()
    return render_template('category.html', articles=articles, categories=categories, category_id=category_id)


# 详情页
@article.route('/article_<int:art_id>/#', methods=['GET', 'POST'])
def detail_index(art_id):
    articles = QuestionModel.query.get(art_id)
    comments = AnswerModel.query.filter(AnswerModel.question_id == art_id).order_by(
        AnswerModel.create_time.desc()).all()
    if request.method == 'GET':
        return render_template('detail_index.html', articles=articles, comments=comments)
    elif request.method == 'POST':
        if hasattr(g, "user") and g.user is not None:
            body = request.form.get('body')
            # 添加评论
            comment_form = AnswerForm(body=body)
            if comment_form.validate():
                n_comment = AnswerModel(content=body, question=articles, author=g.user)
                db.session.add(n_comment)
                db.session.commit()
            elif len(body) <= 1:
                flash('不能低于一个字符', 'warning')
            return redirect(url_for('article.detail_index', art_id=art_id) + '#comments')
        else:
            flash('请先登陆', 'danger')
            return redirect(url_for('auth.login'))

# 评论
@csrf.exempt
@article.route('send_reply', methods=['POST'])
def send_reply():
    if hasattr(g, "user") and g.user is not None:
        replied_body = request.form.get('replied_body')
        comment_id = request.form.get('comment_id')
        # 被回复的评论 在哪个大框里面
        comment = AnswerModel.query.get(comment_id)
        replied_form = AnswerForm(body=replied_body)
        art_id = request.form.get('art_id')
        if replied_form.validate():
            top_comment_id = request.form.get('top_comment_id')
            replied = comment if top_comment_id is None else AnswerModel.query.get(top_comment_id)
            # if top_comment_id is None:
            #     replied = AnswerModel(content=replied_body, author=g.user, replied=comment, question_id=art_id,to_user=comment.author)
            # else:
            #     top_comment = AnswerModel.query.get(top_comment_id)
            replied = AnswerModel(content=replied_body, author=g.user, replied=replied, question_id=art_id,
                                      to_user=comment.author)
            db.session.add(replied)
            db.session.commit()
            print('成功')
        else:
            if not (len(replied_body)):
                flash('评论打点字', 'warning')
        return redirect(url_for('article.detail_index', art_id=art_id) + '#comments')
    else:
        flash('请先登陆', 'danger')
        return redirect(url_for('auth.login'))


# 发布文章
@article.route('/editer/article', methods=['GET', 'POST'])
@login_required
def editer_article():
    if g.user:
        if g.user.is_root:
            if request.method == 'POST':
                a_title = request.form.get('title')
                a_content = request.form.get('content').encode('utf-8')
                category_id = request.form.get('category')
                new_category = request.form.get('new_category')
                if new_category:
                    cate1 = CategoryModel(name=new_category)
                    db.session.add(cate1)
                elif category_id:
                    cate1 = CategoryModel.query.get(category_id)
                else:
                    return redirect(url_for('article.editer_article'))
                # 文章的进一步说明
                explain = request.form.get('explain')
                article1 = QuestionModel(title=a_title, content=a_content, category=cate1, author=g.user,explain=explain)
                db.session.add(article1)
                db.session.commit()
                return redirect(url_for('article.editer_article'))
            categories = CategoryModel.query.all()
            return render_template('editer_article.html', categories=categories)
        else:
            return redirect('/')


# 图片保存路径
@article.route('/upload/')
def upload():
    pass